class WebSocketClient {
  constructor(url,token) {
    this.url = url;
    this.socketTask = null;
    this.heartBeatTimer = null;
    this.reconnectTimer = null;
    this.reconnectCount = 0;
	this.token = token
	try{
		this.connect()
	}catch(e){
		//TODO handle the exception
	}
  }

async  connect() {
    this.socketTask =await uni.connectSocket({
      url: this.url,
     protocols: this.token,
	 complete:() =>{
	 	
	 }
    });
console.log( this.socketTask,' this.socketTask');
    this.socketTask.onOpen(() => {
      console.log('WebSocket connected!');
      this.startHeartBeat();
    });

    this.socketTask.onClose(() => {
      console.log('WebSocket disconnected!');
      clearTimeout(this.heartBeatTimer);
      clearTimeout(this.reconnectTimer);
      if (this.reconnectCount < 30) {
        this.reconnectTimer = setTimeout(() => {
          console.log('WebSocket reconnecting...');
          this.reconnectCount++;
          this.connect();
        },60 * 1000);
      } else {
        console.log('WebSocket reconnect failed after 10 tries.');
      }
    });

    this.socketTask.onError((err) => {
      if (this.reconnectCount < 10) {
        this.reconnectTimer = setTimeout(() => {
          console.log('WebSocket reconnecting...');
          this.reconnectCount++;
          this.connect();
        },  60 * 1000);
      } else {
        console.log('WebSocket reconnect failed after 10 tries.');
      }
    });

    this.socketTask.onMessage((res) => {
		
     	uni.$emit('message', res.data)
    });
  }

  disconnect() {
    if (this.socketTask) {
      this.socketTask.close();
    }
    clearTimeout(this.heartBeatTimer);
    clearTimeout(this.reconnectTimer);
    this.reconnectCount = 0;
  }

  send(data) {
    if (this.socketTask && this.socketTask.readyState === 1) {
      this.socketTask.send({
        data,
        fail: (err) => {
          console.log('WebSocket send message failed:', err);
        }
      });
    }
  }

  startHeartBeat() {
    this.heartBeatTimer = setTimeout(() => {
      this.send('wy-');
      this.startHeartBeat();
    }, 1000);
  }
}

export default WebSocketClient;